#!/usr/bin/env python

"""
This file is part of open-hea.

open-ihm is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.

open-ihm is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with open-ihm.  If not, see <http://www.gnu.org/licenses/>.
"""

__author__ = 'Tiwonge Manda,Brown Msiska'
__credits__ = 'Sarah Mount'
__date__ = 'May 2012'
__version__ = '0.1'

from datetime import date
import os

from openhea.mysql.connector import Connect
from openhea.mysql.connector import errors


class DatabaseInitialiser:
     """Setup open-HEA database
     """
     def __init__(self, config):
         self.config = config
         
         #date of latest DB update: must be reset to latest date when DB changes are being pushed - format yyyy-mm-dd
         self.latestupdatestring = "latest update on 2012-05-16" 
         
     def initialiseDB(self, createdb_sql_filename):
         """ Check if MySQL is running and open-hea database (openheadb) is installed
         """
          
         dbinfo = self.config.dbinfo()
         # assume that mysql server is running and database is installed already
         mysqlstarted = True
         dbinstalled = True
         #dbuptodate = True
         # try connecting to database
         try:
             db = Connect( **dbinfo )
             db.close()
         # interfaceError occurs if MySQL server is not running
         except errors.InterfaceError:
             mysqlstarted = False
         # OperationalError or ProgrammingError happen if the db does not exist
         except ( errors.OperationalError,  errors.ProgrammingError) as e:
             dbinstalled = self.createDatabase(createdb_sql_filename)
             
         dbstatus = dict()
         dbstatus['mysqlstarted'] = mysqlstarted
         dbstatus['dbinstalled'] = dbinstalled
         #dbstatus['dbuptodate'] = dbuptodate
         print dbstatus
     
         return dbstatus
     
     def full_script_filename(self, filename):
         return os.path.join(self.config.schema_script_path(), filename)

     def executeSQL(self, sql_filename, create=False):
         """ Create open-hea database (openheadb)
         """
         sqlfile = file(self.full_script_filename(sql_filename), 'r')
         commands = sqlfile.read()
         commandlist = commands.split(';')
         sqlfile.close()
         try:
             if create:
                 dbinfo = self.config.superuser_dbinfo().copy()
                 del dbinfo['database']
             else:
                 dbinfo = self.config.dbinfo()
             db = Connect(**dbinfo)
             cursor = db.cursor()

             for command in commandlist:
                 if ( not command.isspace() ):
                     cursor.execute(command)
             
             cursor.close()
             db.close()
         
             return True
         
         except errors.InterfaceError:
             return False

     def createDatabase(self, sql_filename):
         try:
             return self.executeSQL(sql_filename, create=True)
         except ( errors.OperationalError,  errors.ProgrammingError):
             print "failed to create database"
             return False
